import path from 'path'
import fs from 'fs-extra'
import xlsx from 'node-xlsx';

export const getFileNameList = () => {
  
}

// 文件是否存在
export const checkIsExist = () => {
  
}

// 转移
export const moveReleaseFileToDist = async (releasePath) => {
  const releaseFile = 'topic'
  const resPath = path.resolve(releasePath, releaseFile)
  csvToXlsFile(resPath)
  await fs.copy(resPath, getReleaseFilePath()).then(() => {
     // copy完删除执行文件
     fs.remove(releasePath)
  })
}

// 同步方法
export const csvToXlsFile =  (filePath) => {
  const files =  fs.readdirSync(filePath)
  try {
    files.forEach((filename) => {
      const s = path.resolve(filePath, filename)
      const xlsxPath = `${s}.xlsx`
      // 先删了防止 convertCsvToXlsx 报错
      const isExists = fs.pathExistsSync(xlsxPath)
      if (isExists) {
        fs.removeSync(xlsxPath)
      }
      const csvData = xlsx.parse(s)
      const fileBuffer = xlsx.build(csvData);
      fs.writeFileSync(xlsxPath, fileBuffer)
    })
  } catch (e) {
    console.warn(e)
  }
}


export const createPydFile = (data) => {
  const { username, keyword, cookie, start_time, end_time } = data
  const only_origin = false
  const p = getPYDFilePath()
  const newPath = path.resolve(getProjectRuneTimePath(), username, keyword)
  const jsonPath = path.resolve(newPath,'topic_config.json')
  return fs.copy(p, newPath).then(async () => {
    await fs.outputFile(jsonPath, JSON.stringify({
      cookie,
      keyword,
      start_time,
      end_time,
      only_origin
    }))
    // 返回路径
    return newPath
  })
}

export const getProjectRuneTimePath = () => {
  return path.resolve(__dirname, '../../../../../', 'dist-runtime')
}

export const getReleaseFilePath = () => {
  return path.resolve(__dirname, '../../../../../', 'release-list')
}


export const getPYDFilePath = () => {
  return path.resolve(__dirname, '../../../../', 'pyd')
}